import cv2
import numpy as np
from sklearn import svm
import pickle


def preprocess_char(char_img):
    # 调整大小为统一尺寸
    resized = cv2.resize(char_img, (20, 20))
    # 计算HOG特征
    win_size = (20, 20)
    cell_size = (5, 5)
    block_size = (10, 10)
    block_stride = (5, 5)
    num_bins = 9
    hog = cv2.HOGDescriptor(win_size, block_size, block_stride, cell_size, num_bins)
    hog_descriptor = hog.compute(resized)
    return hog_descriptor.flatten()


class CharRecognizer:
    def __init__(self):
        self.model = None

    def train(self, X, y):
        self.model = svm.SVC(kernel='rbf', C=1.0, gamma='scale')
        self.model.fit(X, y)

    def save_model(self, filename):
        with open(filename, 'wb') as f:
            pickle.dump(self.model, f)

    def load_model(self, filename):
        with open(filename, 'rb') as f:
            self.model = pickle.load(f)

    def predict(self, char_img):
        features = preprocess_char(char_img)
        return self.model.predict([features])[0]